package com.charmzenus.champion.base.net;

import com.charmzenus.champion.utils.LogUtil;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by a1899 on 2018/4/25.
 */
public class CallbackAdapter<T> implements Callback<T> {

    private CallbackResponse<T> responseListener;

    public CallbackAdapter(CallbackResponse<T> response) {
        this.responseListener = response;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        // 处理回复
        if (!response.isSuccessful()) {

            T result = response.body();
            ResponseInfo info = (ResponseInfo) result;

            if (info == null) return;

            int code = info.code;
            if (code == 0) {
                // 服务器端处理成功，并返回目标数据
                responseListener.success(result);

            } else {
                // 服务器端处理成功，返回错误提示，该信息需要展示给用户
                // 依据code值获取到失败的数据
                responseListener.error(result);
            }

        } else {
            // 联网过程中的异常
            systemError();
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        systemError();
    }

    public void systemError() {
        ErrorInfo info = new ErrorInfo(-1, "网络请求失败");
        responseListener.netError(info);
    }


    public interface CallbackResponse<T> {
        void success(T info);

        void error(T info);

        void netError(ErrorInfo info);
    }
}
